package com.library.view;

import com.library.controller.BorrowController;
import com.library.entity.Pagination;
import com.library.pojo.dto.borrow.BorrowPageQueryDTO;
import com.library.pojo.vo.BorrowVO;
import com.library.result.PageResult;
import com.library.result.Result;
import com.library.view.components.CommonButton;
import com.library.view.components.TipDialog;
import io.yukk1o.easytermui.EasyTermUI;
import io.yukk1o.easytermui.component.Button;
import io.yukk1o.easytermui.component.InputBox;
import io.yukk1o.easytermui.component.Panel;
import io.yukk1o.easytermui.component.Text;
import io.yukk1o.easytermui.component.complex.table.Table;
import io.yukk1o.easytermui.util.PrintUtils;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;

/**
 * 借阅管理面板
 * <p>
 * 包含组件:
 * 顶部：返回按钮、多条件搜索输入框（借阅记录ID/用户ID/图书ID/借阅时间/归还时间）、搜索按钮
 * 中间：所有借阅记录列表
 * 底部：页码显示（当前/最大）、上下页翻页按钮
 * <p>
 * 交互流程:
 * 1. 点击返回/按ESC → 返回上一界面；
 * 2. 点击输入框可调整光标位置，点击搜索按钮 → 筛选并展示匹配记录；
 * 3. 点击翻页按钮 → 执行翻页并回显数据；
 * 4. 选中借阅记录按Enter → 执行强制归还。
 */

public class BorrowManagePanel {
    private final Pagination pagination;
    private final BorrowPageQueryDTO queryDTO;
    private final EasyTermUI easyTermUI = new EasyTermUI();
    private final Table table;
    private Boolean init = false;


    // 明确的表格数据类
    private static class BorrowTableData {
        public final Integer borrowId;
        public final String userName;
        public final String bookName;
        public final String borrowTime;
        public final String returnTime;
        public final Button operationButton;

        public BorrowTableData(Integer borrowId, String userName, String bookName,
                               LocalDateTime borrowTime, LocalDateTime returnTime, Button operationButton) {
            this.borrowId = borrowId;
            this.bookName = bookName;
            this.userName = userName;
            this.borrowTime = borrowTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
            this.returnTime = returnTime != null ? returnTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")) : "未归还";
            this.operationButton = operationButton;
        }
    }

    public BorrowManagePanel() {
        this.pagination = new Pagination();
        pagination.setPageSize(25);
        Panel root = new Panel(0, 0, 120, 40);

        // 标题文本
        Text line1 = new Text(0, 1, 120, 1, "========================================================================================================================");
        Text title = new Text(57, 3, 5, 1, "图书馆系统");
        Text line2 = new Text(0, 5, 120, 1, "========================================================================================================================");

        //分隔线
        Text line3 = new Text(0, 10, 120, 1, "------------------------------------------------------------------------------------------------------------------------");
        root.addComponent(line3);
        root.addComponent(line1);
        root.addComponent(title);
        root.addComponent(line2);

        /// 返回按钮
        CommonButton backButton = new CommonButton(1, 3, " <<<< ", easyTermUI::stop);
        root.addComponent(backButton);

        // 表头列定义
        LinkedHashMap<String, Integer> colMeta = new LinkedHashMap<>();
        colMeta.put("编号", 9);
        colMeta.put("用户名", 20);
        colMeta.put("书籍名", 25);
        colMeta.put("借出时间", 25);
        colMeta.put("归还时间", 25);
        colMeta.put("操作", 11);

        this.table = new Table(0, 11, 25, colMeta);

        this.queryDTO = new BorrowPageQueryDTO(
                pagination.getCurrentPage(), pagination.getPageSize(), null, null, null, null, null
        );

        // 初次加载数据
        refresh(pagination.getCurrentPage());
        init = true;
        root.addComponent(table);

        // 搜索栏
        Text idText = new Text(3, 8, 6, 1, "借阅ID:");
        InputBox idInput = new InputBox(10, 8, 6);
        root.addComponent(idText);
        root.addComponent(idInput);

        Text userText = new Text(20, 8, 6, 1, "用户名:");
        InputBox userInput = new InputBox(27, 8, 6);
        root.addComponent(userText);
        root.addComponent(userInput);

        Button searchBtn = new Button(40, 8, " 搜索 ", (b) -> {
            pagination.setCurrentPage(1);
            queryDTO.setPageNum(pagination.getCurrentPage());
            queryDTO.setBorrowId(parseIntOrNull(idInput.getValue()));
            queryDTO.setUserId(parseIntOrNull(userInput.getValue()));
            refresh(pagination.getCurrentPage());
            table.render();
        });
        root.addComponent(searchBtn);

        /// 页码显示
        Text pageText = new Text(63, 39, 10, 1, getPageInfoText());
        root.addComponent(pageText);

        // 上下页翻页按钮
        Button prevButton = new Button(45, 39, " 上一页 ", (button) -> {
            if (pagination.prev()) {
                refresh(pagination.getCurrentPage());
                pageText.setText(getPageInfoText());
                pageText.render();
            }
        });

        root.addComponent(prevButton);
        Button nextButton = new Button(73, 39, " 下一页 ", (button -> {
            if (pagination.next()) {
                refresh(pagination.getCurrentPage());
                pageText.setText(getPageInfoText());
                pageText.render();
            }
        }));
        root.addComponent(nextButton);

        PrintUtils.clearScreen();
        easyTermUI.init(root);
        // 启动UI
//        try {
//            EasyTermUI easyTermUI = new EasyTermUI().init(root);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
    }

    /**
     * 解析整数或返回 null
     */
    private Integer parseIntOrNull(String value) {
        if (value == null || value.isEmpty()) {
            return null;
        }
        try {
            return Integer.valueOf(value);
        } catch (NumberFormatException e) {
            return null;
        }
    }

    /**
     * 加载表格数据
     */
    private void refresh(int pageNum) {
        Result<PageResult> pageResult = new BorrowController().selectBorrowList(queryDTO);
        queryDTO.setPageNum(pageNum);
        List<BorrowVO> list = pageResult.getData().getRecords();

        List<Object> rows = new ArrayList<>();
        for (BorrowVO item : list) {
            BorrowTableData rowData = new BorrowTableData(
                    item.getBorrowId(),
                    item.getUsername(),
                    item.getName(),
                    item.getBorrowTime(),
                    item.getReturnTime(),
                    new Button(0, 0, "强制归还", (b) -> {
                    BorrowController adminUserController = new BorrowController();
                    Result<String> result = adminUserController.revert(item.getBorrowId());
                    int resultCode = result.getCode();
                    if (result.getCode() == 1) {
                        easyTermUI.mountNoAutoStart(new TipDialog(40, 15, "操作成功"));
                        try {
                            Thread.sleep(500);
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                        pagination.setCurrentPage(1);
                        refresh(pagination.getCurrentPage());
                    } else {
                        easyTermUI.mount(new TipDialog(40, 15, "操作失败"));
                    }
                    easyTermUI.start();
                }));
            rows.add(rowData);
        }

        pagination.setTotal((int) pageResult.getData().getTotal());

        table.setData(rows);
        if (init) {
            table.render();
        }
    }

    /**
     * 更新页码文本
     */
    private void updatePageText(Text text, BorrowPageQueryDTO dto) {
        text.setText("当前页: " + dto.getPageNum());
        text.render();
    }

    private String getPageInfoText() {
        return pagination.getCurrentPage() + " / " + pagination.getMaxPage();
    }


//    /** 测试入口 */
//    public static void main(String[] args) {
//        BorrowManagePanel panel = new BorrowManagePanel();
//        panel.BorrowManagePanel();
//
//        // 保持程序运行
//        final CountDownLatch latch = new CountDownLatch(1);
//        try {
//            latch.await();
//        } catch (InterruptedException e) {
//            Thread.currentThread().interrupt();
//        }
//    }
}